package com.example.musicaiap.data.database

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.example.musicaiap.data.database.dao.CurrentPlaylistDao
import com.example.musicaiap.data.database.dao.PlaylistDao
import com.example.musicaiap.data.database.dao.PlaylistSongDao
import com.example.musicaiap.data.database.dao.SongDao
import com.example.musicaiap.data.database.dao.PlayHistoryDao

/**
 * 音乐数据库
 * Room数据库的入口点，用于持久化存储应用数据
 */
@Database(
    entities = [
        SongEntity::class,
        PlaylistEntity::class,
        PlaylistSongCrossRef::class,
        CurrentPlaylistEntity::class,
        PlayHistoryEntity::class
    ],
    version = 1,
    exportSchema = false
)
@TypeConverters(Converters::class)
abstract class MusicDatabase : RoomDatabase() {
    
    /**
     * 获取歌曲DAO
     */
    abstract fun songDao(): SongDao
    
    /**
     * 获取播放列表DAO
     */
    abstract fun playlistDao(): PlaylistDao
    
    /**
     * 获取播放列表与歌曲关系DAO
     */
    abstract fun playlistSongDao(): PlaylistSongDao
    
    /**
     * 获取当前播放列表DAO
     */
    abstract fun currentPlaylistDao(): CurrentPlaylistDao
    
    /**
     * 获取播放历史DAO
     */
    abstract fun playHistoryDao(): PlayHistoryDao
    
    companion object {
        private const val DATABASE_NAME = "music_database"
        
        @Volatile
        private var INSTANCE: MusicDatabase? = null
        
        /**
         * 获取数据库实例
         * 如果实例不存在，则创建新的实例
         */
        fun getInstance(context: Context): MusicDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    MusicDatabase::class.java,
                    DATABASE_NAME
                )
                    .fallbackToDestructiveMigration() // 如果数据库版本升级，直接删除重建
                    .build()
                INSTANCE = instance
                instance
            }
        }
    }
} 